package com.delu.lock;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.convert.RedisData;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class AdvPayLock {

    @Autowired
    private RedisTemplate redisTemplate;

    public Boolean lock (String key, String value) {

        if (redisTemplate.boundValueOps(key).setIfAbsent(value)) {

            return true;
        }

        Long l = (Long) redisTemplate.boundValueOps(key).get();

        if (l != null && new Date().getTime() >= l) {

            Long oldL = (Long) redisTemplate.boundValueOps(key).getAndSet(value);

            if (l == oldL) {

                return true;
            }
        }

        return false;
    }

    public Boolean unlock(String key, String value) {

        try {

            if (redisTemplate.boundValueOps(key).get().toString().equals(value)) {

                redisTemplate.delete(key);

                return true;

            }

        }catch (Exception e) {

            e.printStackTrace();

        }

        return false;

    }
}
